/**
 * 
 */
package com.effectiv.gooruda.rest.api.service;


import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.jms.core.ProducerCallback;

import com.effectiv.gooruda.rest.api.domain.CloudMessage;

/**
 * @author Dhrubo
 * 
 */

@Slf4j
@AllArgsConstructor
public class DefaultProduerCallback implements ProducerCallback<Message> {

	private CloudMessage message;

	private final long DEFAULT_EXPIRY = 604800L;
	private final long MAX_EXPIRY = 2592000L;
	private final long MAX_DELAY = 604800L;

	@Override
	
	public Message doInJms(Session session, MessageProducer producer)
			throws JMSException {
		ObjectMessage m = session.createObjectMessage(message);
		
		//String correlationId = UUID.randomUUID().toString();
		
		//log.debug("######## correlationId = {}", correlationId);
		
		//m.setJMSCorrelationID(correlationId);

		long delay = message.getDelay();

		if (delay > MAX_DELAY) {
			delay = MAX_DELAY;
		}

		m.setLongProperty(org.hornetq.api.core.Message.HDR_SCHEDULED_DELIVERY_TIME.toString(), System.currentTimeMillis() + delay * 1000);
		
		log.debug("######## Delay = {}", delay);

		long expiry = message.getExpiration();

		if (expiry <= 0) {
			expiry = DEFAULT_EXPIRY;
		}

		else if (expiry > MAX_EXPIRY) {
			expiry = MAX_EXPIRY;
		}

		log.debug("######## Expiry = {}", expiry);
		
		producer.setTimeToLive(expiry * 1000);
		producer.send(m);

		
		
		return m;
	}

}
